package com.sgb.kjwl.view.ui.fragment.self.company

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppLazyFragment
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.FragmentCentrailzedAgentBinding
import com.sgb.kjwl.databinding.ItemAgentCentralizedmingBinding
import com.sgb.kjwl.di.self.DaggerSelfFragComponent
import com.sgb.kjwl.di.self.SelfFragModule
import com.sgb.kjwl.model.entity.self.AgentCentralizedEntity
import com.sgb.kjwl.view.event.self.RefreshUnReadNumEvent
import com.sgb.kjwl.view.widget.manage.GradientBgTextView
import com.sgb.kjwl.viewmodel.self.company.CentralizedMiningViewModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration
import com.swgk.core.util.DateUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject


class AgentCentralizedMiningFragment : AppLazyFragment() {

    private lateinit var mBinding : FragmentCentrailzedAgentBinding

    private var mNo = "" //区分加盟单位还是报价单位
    private lateinit var mAdapter : CentralizedMiningAdapter

    private var isLoadMore = false //是否加载更多
    private var isEnableLoadMore = false//是否能加载更多

    @Inject
    lateinit var mViewModel : CentralizedMiningViewModel

    private var mCallback : UpdateNumCallback ?= null

    override fun onAttach(activity: Activity) {
        super.onAttach(activity)
        if (activity is UpdateNumCallback){
            this.mCallback = activity
        }
    }


    companion object{
        const val TAG = "agentCentralizedMiningFragment"
        const val KEY_NO = "key_no"
        fun newInstance(no : String)  : AgentCentralizedMiningFragment {
            val fragment = AgentCentralizedMiningFragment()
            val bundle = Bundle()
            bundle.putString(KEY_NO, no)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun setupFragmentComponent(appComponent: AppComponent?) {
        super.setupFragmentComponent(appComponent)
        DaggerSelfFragComponent.builder().appComponent(appComponent)
            .selfFragModule(SelfFragModule()).build().inject(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null){
            mNo = requireArguments().getString(AgentAgreementFragment.KEY_NO)!!
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_centrailzed_agent, container, false)
        return mBinding.root
    }

    override fun initView() {
        super.initView()
        initRecyclerView()
        renderLiveData()
    }

    private fun renderLiveData() {
        mViewModel.joinList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (it != null ) {
                if (isLoadMore) {
                    mAdapter.addData(it)
                } else {
                    mAdapter.setNewData(it)
                }
            }
        })
        mViewModel.offerList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (it != null ) {
                if (isLoadMore) {
                    mAdapter.addData(it)
                } else {
                    mAdapter.setNewData(it)
                }
            }
        })
        mViewModel.readPosition.observe(this, {
            if (it != null){
                MainScope().launch(Dispatchers.Main) {
                    delay(800)
                    mAdapter.remove(it)
                    if (mCallback != null){
                        mCallback!!.updateNum()
                    }
                    EventBus.getDefault().postSticky(RefreshUnReadNumEvent.make())
                }
            }
        })
    }

    override fun onLazyLoad() {
        isLoadMore = false
        getDatas()
    }

    fun getDatas() {
        if (mNo == "12"){//加盟单位
           mViewModel.getCentralizedJoinList(isLoadMore)
        } else if (mNo == "13"){//报价单位
            mViewModel.getCentralizedOfferList(isLoadMore)
        }
    }


    private fun initRecyclerView() {
        mBinding.recycleView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                getDatas()
                mBinding.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                getDatas()
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mBinding.recycleView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        mBinding.recycleView.setItemViewCacheSize(100)
        mBinding.recycleView.setHasFixedSize(true)
        mAdapter = CentralizedMiningAdapter(requireContext(), R.layout.item_agent_centralizedming, mNo)
        mAdapter.bindToRecyclerView(mBinding.recycleView)
        val empty = LayoutInflater.from(context).inflate(R.layout.layout_empty_view, mBinding.recycleView, false)
        mAdapter.emptyView = empty
        mBinding.recycleView.addItemDecoration(
            RecyclerCustomDecoration(
                0f,
                0f,
                0f,
                resources.getDimension(R.dimen.dp1), resources.getColor(R.color.color_main_bg)
            )
        )
        mAdapter.setOnItemClickListener(object : BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                if (mAdapter.getItem(position) != null){
                    var item = mAdapter.getItem(position)
                    mViewModel.saveUserReadAgent(item!!.no, position)
                    mViewModel.getH5Url(context!!, item!!.groupBuyNo, 1, item.groupbuyMode)
                }
            }

        })
    }



    class CentralizedMiningAdapter(mContext : Context, @LayoutRes layoutId : Int, no : String) : BaseQuickAdapter<AgentCentralizedEntity, BaseViewHolder>(layoutId){
        private var mItemBinding : ItemAgentCentralizedmingBinding ?= null

        private var mColorSpan : ForegroundColorSpan = ForegroundColorSpan(mContext.resources.getColor(R.color.color_title_medium))

        private var ssb : SpannableStringBuilder ?= null

        private var mNo = no

        override fun convert(helper: BaseViewHolder?, item: AgentCentralizedEntity?) {
              mItemBinding = DataBindingUtil.bind(helper!!.itemView)
              if (mItemBinding != null){
                  mItemBinding!!.entity = item
                  setColorSpan(mContext.resources.getString(if (mNo == "12") R.string.join_purchase_number else R.string.offer_price, item!!.offerPrice + item.unitName), mItemBinding!!.tvPurchaseNum)
                  setColorSpan(mContext.resources.getString(if (mNo == "12") R.string.join_unit else R.string.offer_unit, item.offerCompany), mItemBinding!!.tvJoinUnit)
                  setColorSpan(mContext.resources.getString(if (mNo == "12") R.string.join_agent_centralizedming_address else R.string.offer_agent_centralizedming_address, item.provinceName + item.cityName + item.detailAddress), mItemBinding!!.tvAddress)
                  setColorSpan(mContext.resources.getString(if (mNo == "12") R.string.join_time else R.string.offer_time, DateUtils.timestampToDateSecond(item.offerTime)), mItemBinding!!.tvJoinTime)
                  setType(item, mItemBinding!!.tvType)
              }
        }

        private fun setType(item: AgentCentralizedEntity, tv: GradientBgTextView) {
            when(item.getBuyType()) {
                "需方发起" -> {
                    tv.setColors(R.color.color_secondary_blue_four, R.color.color_secondary_blue_third)
                }
                "企业专项" -> {
                    tv.setColors(
                        R.color.color_secondary_green_easy_fifth,
                        R.color.color_secondary_green_easy_four
                    )
                }
                "供方发起" -> {
                    tv.setColors(
                        R.color.color_secondary_purple_third,
                        R.color.color_secondary_purple
                    )
                }
            }
        }

        private fun setColorSpan(content: String, tv: TextView) {
            ssb = SpannableStringBuilder(content)
            ssb!!.setSpan(mColorSpan, content.indexOf("："), content.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
            tv.text = ssb
        }

    }


    interface UpdateNumCallback{
        fun updateNum()
    }
}